package com.xy.controller.express;


import com.alibaba.fastjson.JSON;
import com.xy.common.base.ApiBaseResponse;

import com.xy.entity.express.express100.ExpressDetail;
import com.xy.entity.express.express100.ExpressResult;
import com.xy.entity.express.express100.NoticeRequest;
import com.xy.entity.express.express100.NoticeResponse;
import com.xy.repository.express.NoticeDataRepository;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Api(value = "快递单回调Controller", description = "快递100推送请求接口")
@RestController
public class OrderCellBack  {

    @Autowired
    private NoticeDataRepository noticeDataRepository;

    @ApiOperation("回调")
    @ResponseStatus(HttpStatus.OK)
    @PostMapping(value = "/cellback")
    @Transactional
    public ResponseEntity CellBackToserver( HttpServletRequest request, HttpServletResponse response) throws  IOException {

        NoticeResponse resp = new NoticeResponse();

        try {

            String param = request.getParameter("param");
            NoticeRequest nReq = JSON.parseObject(param, NoticeRequest.class);//json格式转成对象

            ExpressResult result = nReq.getLastResult();//获取result

            String nu = result.getNu();//result获取nu

            String datas=JSON.toJSONString(result.getData()); //将result的data转成jsonstring


            ExpressDetail ed = new ExpressDetail();
            ed.setNu(nu);

            ed.setData(datas);

            noticeDataRepository.save(ed);
            // 处理快递结果

            resp.setResult(true);
            resp.setReturnCode("200");
            System.out.print(JSON.toJSON(resp)); //这里必须返回，否则认为失败，过30分钟又会重复推送。



            //noticeRequestRepository.save(result);

        } catch (Exception e) {
            resp.setMessage("保存失败" + e.getMessage());
            System.out.print(JSON.toJSON(resp));//保存失败，服务端等30分钟会重复推送。

        }
        return ResponseEntity.ok(ApiBaseResponse.fromHttpStatus(HttpStatus.OK,resp));
    }


}
